<?php

namespace app\api\controller\goods;

use app\api\BaseController;
use app\api\service\GoodsCategoryService;
use app\api\service\GoodsService;
use think\exception\ValidateException;

class GoodsController extends BaseController
{
    /**
     * 获取商品列表
     * */
    public function index()
    {

        $param = $this->request->param();

        try{
            $this->validate($param,[
                'cid' => 'integer',
                'is_subsidy' => 'integer',
                'store_id' => 'require|integer',
                'is_limit_member' => 'integer',
            ]);
        }catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        $goodsList =  GoodsService::getGoodsList($param);

        return json(['code' => 1, 'data' => $goodsList,'msg' => '请求成功!']);
    }

    /**
     * 获取商品详情
     * */
    public function read()
    {
        $goods_id = $this->request->param('goods_id/d');
        if (empty($goods_id)){
            return  json(['code' =>0, 'msg' => '非法参数']);
        }
        $goodsList =  GoodsService::findGoods($goods_id);
        if (!empty($goodsList['content'])){
            $content = $goodsList['content'];
            $suffix = request()->domain();
            $content = str_replace('../..', '',$content);
            $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.JPG|\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
            $content = preg_replace($pregRule, '<img src="' . $suffix . '${1}" style="max-width:100%">', $content);
            // echo $content;exit;
            $goodsList['content'] = $content;
        }
       
        return json(['code' => 1, 'data' => $goodsList,'msg' => '请求成功!']);
    }


    /**
     * 获取首页二级分类加商品
     * */
    public function info()
    {
        $param = $this->request->param();

        if (empty($param['cid'])){
            return json(['code' => 0, 'msg' => '非法参数!']);
        }

        $categories = GoodsCategoryService::findChildCategory($param['cid']);

        $goodsList = GoodsService::getGoodsList($param);

        return json(['code' => 1, 'data' => ['categories' => $categories, 'goodsList' => $goodsList],'msg' => '请求成功!']);
    }


}